<template>
  <div>
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      :error.sync="error"
      error-text="请求失败，点击重新加载"
      @load="onLoad"
    >
      <van-cell
        v-for="(item, index) in result"
        :key="index"
        :title="item.title"
        @click="Godetail(item.art_id)"
      />
    </van-list>
  </div>
</template>

<script>
import { getSearchResultsAPI } from '@/api'
export default {
  props: {
    keywords: {
      type: String
    }
  },
  data() {
    return {
      result: [],
      loading: false,
      finished: false,
      error: false,
      page: 1
    }
  },
  created() {
    this.getSearchResultsAPI()
  },
  methods: {
    async getSearchResultsAPI() {
      try {
        const { data } = await getSearchResultsAPI(this.keywords, this.page)
        if (this.page == 1) {
          this.result = data.data.results
        } else {
          this.result.push(...data.data.results)
          if (data.data.results.length < 10) {
            this.finished = true
          }
        }
        this.loading = false
        // console.log(this.result)
      } catch (error) {
        this.error = true
      }
    },
    onLoad() {
      // 异步更新数据
      // setTimeout 仅做示例，真实场景中一般为 ajax 请求
      // setTimeout(() => {
      //   // 加载状态结束
      //   this.loading = false
      //   // 数据全部加载完成
      //   if (this.result.length >= this.result.length) {
      //     this.finished = true
      //   }
      // }, 1000)
      this.page++
      this.getSearchResultsAPI()
    },
    Godetail(id) {
      // 路由传参
      this.$router.push(`/detail/${id}`)
      // this.$store.commit('SET_TOKEN', id)
    }
  }
}
</script>

<style></style>
